// me.js
const requester = require('../../common/requester.js');
const EventEmitter = require('../../common/EventEmitter.js');
const util = require('../../common/util.js');
const user = require('../../common/user.js');
const fans = require('../../utils/fans.js');
const $$onLoad = require('../../appLoaded/onLoad');
const app = getApp();

Page({
    result: {},
    data: {
        tabMap: {
            'works': '作品',
            'likes': '喜欢',
        },
        imageList: [],
        actions: ['contact'],
        hasMessage: true,
        hasNewMessage: false,
        isLastPage: true,
        isAudit: true,
        isAuthed: true,
        showFAB: true
    },

    onLoad: function (param) {
        this.userId = param.userId;
        $$onLoad()
            .then(() => {
                let isAudit = app.globalData.isAudit,
                    isAuthed = app.globalData.isAuthed;

                this.setData({
                    isAudit,
                    isAuthed
                });

                if (isAuthed) {
                    this.init(param);
                }
            });
        this.initTab();
    },

    onPullDownRefresh: function () {
        console.log("onPullDownRefresh.....");
        this.getData(false);
    },

    onPullDownStop: function () {
        wx.stopPullDownRefresh();
    },

    init: function () {
        this.setData({
            isAuthed: true,
            showFAB: !!this.userId,
            isAudit: app.globalData.isAudit
        });
        this.getUserInfo();
        this.getData(false);
        EventEmitter.addListener('backFormSend', () => {
            this.getData(false);
        });
    },

    initTab: function () {
        let tabs = [],
            tabMap = this.data.tabMap,
            pageIndex = {};

        for (let key in tabMap) {
            tabs.push({
                name: tabMap[key],
                key: key,
                count: 0,
                selected: false
            })
        }
        tabs[0].selected = true;

        this.pageIndex = pageIndex;

        this.setData({
            currTab: tabs[0].key,
            tabs
        })
    },

    //为获得总关注图片数，先请求一次myLikeList
    getLikeCount: function () {
        let me = this;
        let userId = this.userId;
        requester.request({
            url: requester.service.myLikeList,
            data: {
                userId: userId || '',
                pageIndex: 1
            }
        }).then(res => {
            let tabs = me.data.tabs;
            tabs.forEach(item => {
                if (item.key === 'likes') {
                    item.count = res.data.totalCount || 0;
                }
            });
            me.setData({
                tabs
            })
        });
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        this.getData(true);
    },

    /**
     * 用户数据获取成功。
     * 分别获取我的资源列表,我喜欢的资源列表。
     */
    getUserInfo: function () {
        let userId = this.userId;
        this.showDialog({title: "正在请求数据...", show: true});
        user.getThirdUserInfo(userId)
            .then(user => {
                this.setData({
                    user: {
                        name: user.nickName,
                        avatar: user.avatarUrl,
                        introduction: user.introduction,
                        publishCount: user.publishCount,
                        followCount: user.followCount,
                        fansCount: user.fansCount,
                        userId: user.id
                    },
                    isFollowed: user.isFollowed
                }, () => {
                    wx.hideLoading();
                });
            });
    },


    /**
     * 获取数据唯一入口。
     * @param isLoadMore
     */
    getData: function (isLoadMore) {

        let currTab = this.data.currTab;

        if (isLoadMore) {
            this.pageIndex[currTab]++;
        } else {
            this.pageIndex[currTab] = 1;
        }

        this.getListDataByTabName()
            .then(resourceLi => {
                if (resourceLi) {
                    util.addModeToList(resourceLi);
                    if (isLoadMore) {
                        let tmpLi = this.result[currTab] || [];
                        resourceLi = tmpLi.concat(resourceLi);
                    }
                    this.result[currTab] = resourceLi;
                }
                this.setData({
                    imageList: this.result[currTab] || null
                }, () => {
                    this.onPullDownStop();
                    this.onLoaded = true;
                })
            });
    },

    /**
     * 根据不同的 tabName 请求不同的种类的列表数据。
     * 不同类型tab请求分页的方式也不一样 offsetId或者pageIndex
     * 请求完了数据之后,
     */

    getListDataByTabName: function () {
        let userId = this.userId,
            currTab = this.data.currTab,
            pageIndex = this.pageIndex[currTab];

        this.showDialog({title: "正在请求数据...", show: pageIndex == 1});
        // No cache, the request...

        let service = {
            'works': requester.service.mySendList,
            'likes': requester.service.myLikeList,
        };

        return requester.request({
            url: service[currTab],
            data: {
                ...userId ? {
                    userId: userId,
                } : {},
                offsetId: pageIndex === 1 ? "" : pageIndex,
                pageIndex: pageIndex || 1
            }
        }).then(res => {
            wx.hideLoading();
            return res.data && res.data.groupList;
        })
    },


    addImage: function () {
        wx.chooseImage({
            count: 1,
            success: (res) => {
                let tempFilePath = res.tempFilePaths[0];
                wx.navigateTo({
                    url: `../send/send?url=${tempFilePath}&from=profile`
                });
            }
        });
    },

    // 进入消息页面
    msgTap: function (e) {
        wx.navigateTo({
            url: '../message/message'
        });
    },

    // 进入编辑页面
    editSelf: function () {
        wx.navigateTo({
            url: '../editSelf/editSelf'
        });
    },


    // 单个图片点击
    cellTap: function (e) {
        const curImage = e.currentTarget.dataset.image;
        wx.navigateTo({
            url: '../pictureDetail/pictureDetail?' + "id=" + curImage.id
        });
    },

    tabItemTap: function (e) {
        let currTab = e.target.dataset.tap;
        let tabs = this.data.tabs;
        tabs.forEach(item => {
            item.selected = item.key === currTab;
        });
        this.setData({
            tabs,
            currTab: currTab
        }, () => {
            let imageList = this.result[currTab];
            if (imageList && imageList.length) {
                this.setData({
                    imageList: imageList
                })
            } else {
                this.getData(false);
            }
        });
    },

    onShareAppMessage: function (res) {
        console.log(this.data.user.userId);
        return {
            title: '我的最佳主页',
            path: '/pages/thirdUser/thirdUser?userId=' + this.data.user.userId,
        }
    },

    showDialog: function (obj) {
        if (obj.show && !this.onLoaded) {
            wx.showLoading({
                title: obj.title,
                mask: true
            });
        } else {
            wx.hideLoading();
        }
    },

    follow: function () {
        let id = this.userId;
        fans.follow(id)
            .then((res) => {
                if (res) {
                    wx.showToast({
                        title: '关注成功'
                    });
                    this.setData({
                        isFollowed: 1
                    })
                }
            })
    },
    unfollow: function () {
        let id = this.userId;
        fans.unfollow(id)
            .then((res) => {
                if (res) {
                    wx.showToast({
                        title: '已取消关注'
                    });
                    this.setData({
                        isFollowed: 0
                    })
                }
            })
    },

    viewFollowFans: function (e) {
        let type = e.target.dataset.type,
            id = this.data.user.userId;
        wx.navigateTo({
            url: `../followList/followList?type=${type}&id=${id}`
        });
    }
});